package com.fengkun.integration.dto;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fengkun.integration.common.trace.TraceUtil;
import lombok.*;

import java.io.Serializable;


/**
 * 统一API响应结果(Result)封装
 *
 * @author Chill
 */
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude
public class ResultDTO<T> implements Serializable {

    /**
     * 序列化ID
     */
    private static final long serialVersionUID = 1L;


    /**
     * 错误码
     */
    private String code;

    /**
     * 错误信息
     */
    private String message;

    /**
     * 是否成功
     */
    private boolean success;

    /**
     * 返回数据
     */
    private T data;

    /**
     * 时间戳
     */
    private long st;

    /**
     * traceId
     */
    private String lid;


    /**
     * 结果dto
     *
     * @param data 数据
     * @param msg  返回信息
     */
    public ResultDTO(String code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.message = msg;
        this.success = "200".equals(code);
        this.lid = TraceUtil.INSTANCE.getTraceData().getTraceId();
        this.st = System.currentTimeMillis();
    }

    public ResultDTO(String code, String msg) {
        this.code = code;
        this.message = msg;
        this.success = "200".equals(code);
        this.lid = TraceUtil.INSTANCE.getTraceData().getTraceId();
        this.st = System.currentTimeMillis();
    }

    public ResultDTO(String code) {
        this.code = code;
        this.success = "200".equals(code);
        this.lid = TraceUtil.INSTANCE.getTraceData().getTraceId();
        this.st = System.currentTimeMillis();
    }

    /**
     * 成功
     *
     * @return {@link ResultDTO}<{@link T}>
     */
    public static <T> ResultDTO<T> success(T data, String msg) {
        return new ResultDTO<>("200", data, msg);
    }

    /**
     * 成功
     *
     * @param data 数据
     * @return {@link ResultDTO}<{@link T}>
     */
    public static <T> ResultDTO<T> success(T data) {
        return new ResultDTO<>("200", data, "成功");
    }


    /**
     * 返回R
     *
     * @param code 状态码
     * @param msg  消息
     * @param <T>  T 泛型标记
     * @return R
     */
    public static <T> ResultDTO<T> fail(String code, String msg) {
        return new ResultDTO<>(code, null, msg);
    }

    /**
     * 返回R
     *
     * @param <T> T 泛型标记
     * @return R
     */
    public static <T> ResultDTO<T> fail(String code) {
        return new ResultDTO<>(code);
    }


}
